package code.D1217;

import java.util.LinkedList;

/**
 * author : yeswater
 * date : 2023/12/18
 */

public class T234 {
    // 超时
    public boolean isPalindrome2(ListNode head) {
        LinkedList<Integer> list = new LinkedList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        for (int i = 0; i < list.size() / 2; i++) {
            if (list.get(i) != list.get(list.size() - i - 1)) {
                return false;
            }
        }
        return true;
    }
    
    public boolean isPalindrome(ListNode head) {
        //边界条件不用忘记了
        if(head==null || head.next==null) {
            return true;
        }
        ListNode p = new ListNode(-1);
        ListNode low = p;
        ListNode fast = p;
        p.next = head;
        //快慢指针不断迭代，找到中间节点
        while(fast!=null && fast.next!=null) {
            low = low.next;
            fast = fast.next.next;
        }
        ListNode cur = low.next;
        ListNode pre = null;
        low.next = null;
        low = p.next;
        //将链表一分为二之后，反转链表后半部分
        while(cur!=null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        //将链表前半部分和 反转的后半部分对比
        while(pre!=null) {
            if(low.val!=pre.val) {
                return false;
            }
            low = low.next;
            pre = pre.next;
        }
        return true;
    }
    
    private static class ListNode {
        int val;
        ListNode next;
        
        ListNode() {
        }
        
        ListNode(int val) {
            this.val = val;
        }
        
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
